//
//  HomeRefreshControl.swift
//  Super_WeiBo
//
//  Created by SuperMac on 16/5/4.
//  Copyright © 2016年 lc. All rights reserved.
//

import UIKit

class HomeRefreshControl: UIRefreshControl
{
    override init() {
        super.init()
        // 初始化UI
        setUpUI()
    }

    private func setUpUI()
    {
        // 添加子控件
        addSubview(refreshView)
        // 布局子控件
        refreshView.xmg_AlignInner(type: XMG_AlignType.Center, referView: self, size: CGSize(width: 170, height: 60))
        // 添加监听
        addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions.New, context: nil)
    }
    
    /// 记录是否要翻转箭头
    private var rotationArrowFlag = false
    /// 加载动画标记
    private var loadingViewAnimFlag = false
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>)
    {
        // 过滤掉不需要的数据
        if frame.origin.y >= 0
        {
            return
        }
        
        // 是否已经触发刷新事件
        if refreshing && !loadingViewAnimFlag
        {
            loadingViewAnimFlag = true
            // 显示刷新图标并转圈
            refreshView.startLoadingViewAnim()
            return
        }
        
        if (frame.origin.y >= -50) && rotationArrowFlag
        {
//            print("大于 -50")
            refreshView.retationArrowIcon(rotationArrowFlag)
            rotationArrowFlag = false
        }
        else if (frame.origin.y < -50) && !rotationArrowFlag
        {
//            print("小于 -50")
            refreshView.retationArrowIcon(rotationArrowFlag)
            rotationArrowFlag = true
        }
    }
    
    /**
     系统自带停止刷新方法
     */
    override func endRefreshing() {
        super.endRefreshing()
        
        // 停止加载动画
        refreshView.stopLoadingViewAnim()
        // 复位标记
        loadingViewAnimFlag = false
    }
    
    // MARK: - 懒加载
    private lazy var refreshView: HomeRefreshView = HomeRefreshView.refreshView()
    
    // 析构函数
    deinit
    {
        // 移除监听
        removeObserver(self, forKeyPath: "frame")
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

class HomeRefreshView: UIView
{
    @IBOutlet weak var loadingView: UIImageView!
    @IBOutlet weak var tipView: UIView!
    @IBOutlet weak var arrowIcon: UIImageView!
    
    /**
     旋转箭头
     */
    func retationArrowIcon(flag: Bool)
    {
        // 处理箭头旋转角度，
        var angle = M_PI
        angle += flag ? 0.001 : -0.001
        UIView.animateWithDuration(0.2) { 
            self.arrowIcon.transform = CGAffineTransformRotate(self.arrowIcon.transform, CGFloat(angle))
        }
    }
    /**
     开始加载动画
     */
    func startLoadingViewAnim()
    {
        tipView.hidden = true
        let anim = CABasicAnimation(keyPath: "transform.rotation")
        anim.toValue = 2 * M_PI
        anim.duration = 1
        anim.repeatCount = MAXFLOAT // 循环次数
        anim.removedOnCompletion = false // 页面切换，动画不停
        loadingView.layer.addAnimation(anim, forKey: nil)
        
    }
    /**
     停止加载动画
     */
    func stopLoadingViewAnim()
    {
        tipView.hidden = false
        loadingView.layer.removeAllAnimations()
    }
    class func refreshView() -> HomeRefreshView
    {
        return NSBundle.mainBundle().loadNibNamed("HomeRefreshView", owner: nil, options: nil).last as! HomeRefreshView
    }
}


